#include <stdio.h>
#include <malloc.h>
#include <mpi.h>

#define MAXNUM 1000

int main(int argc, char **argv)
{ 
	int *arr, *eacharr, *maxarr, eachlen, size, rank, i, each_max, max;
	arr = NULL;
	eacharr = NULL;
	maxarr = NULL;
	MPI_Comm comm = MPI_COMM_WORLD;
	MPI_Init(&argc, &argv); 
	MPI_Comm_size(comm, &size);  
	MPI_Comm_rank(comm, &rank);
	eachlen = MAXNUM / size;
	if (rank == 0)  
	{  
		arr = (int *)malloc(sizeof(int) * MAXNUM);
		maxarr = (int *)malloc(sizeof(int) * size);
		for(i =0;i<MAXNUM;i++)
			arr[i] = i+1;
	}
	eacharr = (int *)malloc(sizeof(int) * eachlen);
	MPI_Scatter(arr, eachlen, MPI_INT, eacharr, eachlen, MPI_INT, 0, MPI_COMM_WORLD);
	each_max = eacharr[0];
	for(i=0 ;i<eachlen; i++)
		if(eacharr[i] > each_max)
			each_max = eacharr[i];
	printf("max of rank %d is %d\n", rank, each_max);
	MPI_Gather(&each_max, 1, MPI_INT, maxarr, 1, MPI_INT, 0, MPI_COMM_WORLD);
	if(rank == 0)
	{
		max = maxarr[0];
		for(i=0; i<size; i++)
			if(maxarr[i] > max)
				max = maxarr[i];
		printf("max of all is :%d\n",max);
	}
	MPI_Finalize(); 
	return 0; 
} 